package com.eportal.action.background;

import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.domain.Sysmenu;
import com.eportal.domain.Sysopt;
import com.eportal.domain.Sysroles;
import com.eportal.service.SysRolesService;
import com.eportal.service.SysmenuService;
import com.eportal.util.BeanMapUtils;
import com.eportal.util.HomePageConfig;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 
 * @author chencheng
 *
 */
public class AuthAction extends BaseAction implements ModelDriven<Sysmenu> {

    private static Logger log = Logger.getLogger(AuthAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();
    @Autowired
    private SysmenuService resourceService;
    @Autowired
    private SysRolesService sysRolesService;
    @Resource(name="sysmenuService")
	 private SysmenuService sysmenuService;
    @Resource(name="dao")
	private BaseDAO dao;
    private static String MSGURL="/admin/userMsg_listNoticeView.action";
    private static String MSGURLUPDATE="/admin/userMsg_editView.action";
    private static String MSGURLDEAIL="/admin/userMsg_noticeDetailView.action";
	/**
     * 加载菜单
     * @author chencheng
     */
    public void menus() throws IOException {
    	String mpid = getRequest().getParameter("mpid");
    	String homePageConfig = HomePageConfig.WUYEJIAOFEI;
    	String propertyPaySid = homePageConfig.split(",")[0];//物业缴费sid
    	String homePageConfig2 = HomePageConfig.SHUIFEI;
    	String waterPaySid = homePageConfig2.split(",")[0];//水费缴费sid
    	String homePageConfig3 = HomePageConfig.TINGCHEFEI;
    	String stopPaySid = homePageConfig3.split(",")[0];//停车缴费sid
    	List<Sysmenu> sysmenus = null;
    	Map<String, Object> map = (Map<String, Object>) getSession().getAttribute("auths");
    	
    	if(StringUtils.isNotBlank(mpid)){
    		if(propertyPaySid.equals(mpid)){//缴费管理
    			sysmenus = getProperMenus(propertyPaySid,"1");
    		}else if(waterPaySid.equals(mpid)){//水费缴费管理
    			sysmenus = getProperMenus(waterPaySid,"2");
    		}else if(stopPaySid.equals(mpid)){//停车费缴费管理
    			sysmenus = getProperMenus(stopPaySid,"3");
    		}else{
    		sysmenus = (List<Sysmenu>) map.get("menus");
    		for (Sysmenu menu : sysmenus) {
    			String url = menu.getmUrl();
    			if (url != null && url.trim().length() > 0) {
    				String[] temp = url.split(",");
    				menu.setmUrl(temp[0]);
    			}
    		}
    	}
    	}else{
    		sysmenus = (List<Sysmenu>) map.get("menus");
    		for (Sysmenu menu : sysmenus) {
    			String url = menu.getmUrl();
    			if (url != null && url.trim().length() > 0) {
    				String[] temp = url.split(",");
    				menu.setmUrl(temp[0]);
    			}
    		}
    	}
    	responseBody(sysmenus);
    }
    
    public List<Sysmenu> getProperMenus(String sid, String type){
    	//物业缴费等菜单集合
        List<Sysmenu> propertyPayMenus = new ArrayList<Sysmenu>();
        int userRole =  (Integer) getSession().getAttribute("userRole");
        Sysopt user = (Sysopt) getSession().getAttribute("user");
        
        StringBuffer sbsql = new StringBuffer();
        sbsql.append("select s.sid,s.mname,s.murl,s.mpno,s.mlevel,s.msort,s.misleaf,s.status,s.mtype,s.type as ttype,s.mcname,s.picname from sysmenu s where s.sid=");
        sbsql.append(sid);
		if(userRole ==5 || userRole ==6){
			sbsql.append(" union all ");
			sbsql.append("select * from (select m.sid as sid,m.item_name as mname,'/admin/propertyPay_listPropertyPayView.action?type=");
			sbsql.append(type);
			sbsql.append("'|| '&' ||'sid='||m.sid as murl,'");
			sbsql.append(sid);
			sbsql.append("' as mpno,1 as mlevel,'1'as msort,'1'as misleaf,'1'as status,'2'as mtype,0 as ttype,m.item_name as mcname,'' as picname  from fee_main m where m.type=");
			sbsql.append(type);
			sbsql.append(" and m.communityid=");
			sbsql.append(user.getCommunityId());
			sbsql.append(" order by m.sid desc)");
		}
			
		List<Map<String, Object>> listSysmenuMap = dao.queryBySql(sbsql.toString());
		
		if (listSysmenuMap != null && listSysmenuMap.size()>0) {
			propertyPayMenus = sysmenuService.getSysmenu(listSysmenuMap);
		}
        return propertyPayMenus;
    }
	/**
     * 加载所有菜单，判断连接权限
     * @author chencheng
     */
    public void menusAll() throws IOException {
    	Map<String, Object> map = (Map<String, Object>) getSession().getAttribute("auths");
    	List<Sysmenu> sysmenus = (List<Sysmenu>) map.get("menusAll");
//    	for (Sysmenu menu : sysmenus) {
//    		String url = menu.getmUrl();
//    		if (url != null && url.trim().length() > 0) {
//    			String[] temp = menu.getmUrl().split(",");
//    			menu.setmUrl(temp[0]);
//    		}
//    	}
    	responseBody(sysmenus);
    }


    /**
     * 加载按钮
     * @author chencheng
     */
    public void buttons() throws IOException {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        List<Sysmenu> resources = new ArrayList();
        String url = getRequest().getParameter("url");
        String type = getRequest().getParameter("type");
        if(StringUtils.isNotBlank(type)){
        	url = url+"?type="+type;
        }
        if (MSGURLUPDATE.equals(url) || MSGURLDEAIL.equals(url)) {
        	url= MSGURL;
		}
        Map<String, Object> map = (Map<String, Object>) getSession().getAttribute("auths");
        map = (Map<String, Object>) map.get("buttons");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            if (key.contains(url)) {
            	resources.addAll((List<Sysmenu>) entry.getValue());
            }
        }
        if (resources != null && resources.size() > 0) {
            for (Sysmenu r : resources) {
                Map<String, Object> m = BeanMapUtils.toMap(r);
                result.add(m);
            }
        }
        responseBody(result);
        return;
    }

    /**
     * 资源管理
     * @author chencheng
     */
    public String listView() {
        return "listView";
    }
    
    /**
     * 资源列表
     * @author chencheng
     */
    public void list() throws Exception {
        JqGridPager page = new JqGridPager();
        setPage(getRequest(), page);
        List<Map<String, Object>> roles = resourceService.list(page);
        jqGridQueryMap(Sysmenu.class, getRequest(), roles, getResponse(), page);
    }


    /**
     * 资源修改
     * @author chencheng
     */
    public String updateView() {
        Sysmenu sysmenu = resourceService.get(getModel().getSid());
        getRequest().setAttribute("sysmenu", sysmenu);
        return "updateView";
    }

    /**
     * 资源修改保存
     */
    public void update() {
    	Sysmenu sysmenu = getModel();
    	result = resourceService.updateMethod(sysmenu);
        responseBody(result);
    }
    
    
    /**
     * 资源新增
     * @author chencheng
     */
    public String addView() throws Exception {
        getRequest().setAttribute("mPno", getModel().getSid());
        if (getModel().getmName() != null && getModel().getmName().trim().length() > 0) {
            getRequest().setAttribute("mName", URLDecoder.decode(getModel().getmName(), "UTF-8"));
        }
        getRequest().setAttribute("mLevel", getModel().getmLevel());
        return "addView";
    }

    /**
     * 资源新增保存
     * @author chencheng
     */
    public void add(){
    	Sysmenu sysmenu = getModel();
    	result = resourceService.addMethod(sysmenu);
        responseBody(result);
    }
   

    /**
     * 资源删除
     * @author chencheng
     */
    public void delete() {
    	Long sid = getModel().getSid();
    	result = resourceService.deleteMethod(sid);
        responseBody(result);
    }
    
    

    /**
     * 角色中资源树
     */
    public void tree() throws IOException {
    	try{
    		List<Sysmenu> sysmenus = null;
        	List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        	String type = sysmenu.getmType();
        	if ("1".endsWith(type)) {//type传的是操作员的角色的isAdmin，去查找role里的mlist
        		Sysroles role = sysRolesService.get(sysmenu.getSid());
        		sysmenus = resourceService.listMenu(role);
    		}else{
    			Map<String, Object> map = (Map<String, Object>) getSession().getAttribute("auths");
    			sysmenus = (List<Sysmenu>) map.get("sysmenus");
    		}
             for (Sysmenu r : sysmenus) {
                 Map<String, Object> obj = new HashMap<String, Object>();
                 obj.put("name", r.getMcname());
                 obj.put("id", r.getSid());
                 obj.put("pId", r.getmPno());
                 result.add(obj);
             }
            responseBody(result);
    	}catch(Exception e){
    		log.error(this, e);
    	}
    }
    

    /**
     * 积分列表
     * @author chencheng
     */
    public void scoreList() throws Exception {
    	String where =" 1=1 and s.type = 1 and s.mType='2' order by sid";
    	List<Map<String, String>> roles = resourceService.scoreList(where);;
        responseBody(roles);
    }
    
    
    private Sysmenu sysmenu = new Sysmenu();

    @Override
    public Sysmenu getModel() {
        return sysmenu;
    }
}
